
//
// 版权所有 (c) 2021-2023 JR
//
// 特此免费授予获得本软件的任何人以处理本软件的权利，但须遵守以下条件：在所有副本或重要部分的软件中必须包括上述版权声明和本许可声明。
//
// 软件按“原样”提供，不提供任何形式的明示或暗示的保证，包括但不限于对适销性、适用性和非侵权的保证。
// 在任何情况下，作者或版权持有人均不对任何索赔、损害或其他责任负责，无论是因合同、侵权或其他方式引起的，与软件或其使用或其他交易有关。

using Magicodes.ExporterAndImporter.Core.Models;
using Minio;
using Minio.DataModel;
using Nest;
using NewLife.Reflection;
using NewLife.Serialization;
using Newtonsoft.Json.Linq;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Logical;
using SqlSugar.Extensions;

namespace EMC.VISITOR.Core.Service;

/// <summary>
/// 系统用户服务
/// </summary>
[ApiDescriptionSettings(MyBusConst.GroupName, Order = 490)]
public class SysUserService : IDynamicApiController, ITransient
{
    private readonly UserManager _userManager;
    private readonly SqlSugarRepository<SysUser> _sysUserRep;
    private readonly SysOrgService _sysOrgService;
    private readonly SysUserExtOrgService _sysUserExtOrgService;
    private readonly SysUserRoleService _sysUserRoleService;
    private readonly SysConfigService _sysConfigService;
    private readonly SysCacheService _sysCacheService;
    protected readonly IHttpClient _resilienceHttpClient;
    public SysUserService(UserManager userManager,
        SqlSugarRepository<SysUser> sysUserRep,
        SysOrgService sysOrgService,
        IHttpClient httpClient,
        SysUserExtOrgService sysUserExtOrgService,
        SysUserRoleService sysUserRoleService,
        SysConfigService sysConfigService,
        SysCacheService sysCacheService)
    {
        _userManager = userManager;
        _sysUserRep = sysUserRep;
        _sysOrgService = sysOrgService;
        _sysUserExtOrgService = sysUserExtOrgService;
        _sysUserRoleService = sysUserRoleService;
        _sysConfigService = sysConfigService;
        _sysCacheService = sysCacheService;
        _resilienceHttpClient = httpClient;
    }

    /// <summary>
    /// 获取用户分页列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取用户分页列表")]
    public async Task<SqlSugarPagedList<SysUser>> Page(PageUserInput input)
    {
        // 获取用户拥有的机构集合
        var userOrgIdList = await _sysOrgService.GetUserOrgIdList();
        List<long> orgList = null;
        if (input.OrgId > 0)  // 指定机构查询时
        {
            orgList = await _sysOrgService.GetChildIdListWithSelfById(input.OrgId);
            orgList = _userManager.SuperJR ? orgList : orgList.Where(u => userOrgIdList.Contains(u)).ToList();
        }
        else // 各管理员只能看到自己机构下的用户列表
        {
            orgList = _userManager.SuperJR ? null : userOrgIdList;
        }

        return await _sysUserRep.AsQueryable()
            .Where(u => u.AccountType != AccountTypeEnum.SuperJR)
            .WhereIF(orgList != null, u => orgList.Contains(u.OrgId))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Account), u => u.Account.Contains(input.Account))
            .WhereIF(!string.IsNullOrWhiteSpace(input.RealName), u => u.RealName.Contains(input.RealName))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Phone), u => u.Phone.Contains(input.Phone))
            .OrderBy(u => u.OrderNo)
            .ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 增加用户
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [UnitOfWork]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    [DisplayName("增加用户")]
    public async Task<long> AddUser(AddUserInput input)
    {
        var isExist = await _sysUserRep.AsQueryable().Filter(null, true).AnyAsync(u => u.Account == input.Account);
        if (isExist) throw Oops.Oh(ErrorCodeEnum.D1003);

        var password = await _sysConfigService.GetConfigValue<string>(CommonConst.SysPassword);

        var user = input.Adapt<SysUser>();
        user.Password = CryptogramUtil.Encrypt(password);
        var newUser = await _sysUserRep.AsInsertable(user).ExecuteReturnEntityAsync();
        input.Id = newUser.Id;

        await OperationWchatUser(newUser);
        await UpdateRoleAndExtOrg(input);

        return newUser.Id;
    }
    /// <summary>
    /// Add用户时如果满足条件则会发送邀请通知到微信，Update用户时如果用户不存在企业微信通讯录时才会发送邀请，否则不发送邀请
    /// </summary>
    /// <param name="user"></param>
    /// <returns></returns>
    public async Task OperationWchatUser(SysUser user)
    {
        //包含下划线代表是没有手机号的
        if (user.Phone.IsNullOrEmpty() || user.Phone.Contains("-"))
            return;
        if (user.WchatInvite.HasValue && user.WchatInvite.Value == true)
        {
            SysUserWchat sysUserWchat = new SysUserWchat();
            sysUserWchat.IsSend = false;
            sysUserWchat.UserId = user.Id;
            await _sysUserRep.Context.MyInsertable<SysUserWchat>(sysUserWchat).ExecuteCommandAsync();
        }
        #region 内网走不通，只能走外网

        //List<dept_user> wchatUserList = new List<dept_user>();
        //var wchatGetUserIdsResponseString = await WarnGetUserIds();
        //var result = wchatGetUserIdsResponseString.ToJsonEntity<WchatReulst>();
        //if (result.success)
        //{
        //    JObject obj = JObject.Parse(wchatGetUserIdsResponseString);
        //    wchatUserList = obj[nameof(dept_user)].ToString().ToJsonEntity<List<dept_user>>();
        //}
        //if (!wchatUserList.Any(r => r.userid == user.JobNum))
        //{
        //    var config = await CommonUtil.GetConfigValue("visitor_wchat_token_create");
        //    var wchatTokenRequestConfig = config.Split(',');
        //    await WarnCreateUser(user.JobNum, user.RealName, user.Phone, wchatTokenRequestConfig[0], wchatTokenRequestConfig[1]);
        //}

        #endregion
    }

    private string GetChatId(string val)
    {
        if (val == "in30m")
        {
            return "emcChat001";
        }
        if (val == "30~60m")
        {
            return "emcChat002";
        }
        if (val == "on60m~120m")
        {
            return "emcChat003";
        }
        if (val == "on120m")
        {
            return "emcChat004";
        }
        return "";
    }
    #region 企业微信邀请发送由自动任务去处理，用户会发送到SysUserWchat表
    /// <summary>
    /// 发送企业微信邀请信息给到用户
    /// </summary>
    /// <param name="userid"></param>
    /// <param name="name"></param>
    /// <param name="mobile"></param>
    /// <param name="corpid"></param>
    /// <param name="corpsecret"></param>
    /// <returns></returns>
    public async Task<string> WarnCreateUser(string userid, string name, string mobile, string corpid = "ww19dea3c4dd73f82a", string corpsecret = "EKjjfwf7SNytft5opCqgYPHKA6aySQIGAyU_iuzeMwA")
    {
        string accessToken = _sysCacheService.Get<string>(CacheConst.KeyQyvxTokenAddUser);
        if (accessToken == null)
        {
            string url = $"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={corpsecret}";
            var tokenRes = await _resilienceHttpClient.GetStringAsync(url);
            var jsonObj = JsonConvert.DeserializeObject<JObject>(tokenRes);
            accessToken = jsonObj["access_token"].Value<string>();
            var expiresIn = jsonObj["expires_in"].Value<int>();
            _sysCacheService.Set(CacheConst.KeyQyvxTokenAddUser, accessToken, TimeSpan.FromTicks(expiresIn * TimeSpan.TicksPerSecond));
        }
        string url2 = "https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token=" + accessToken;
        var item = new
        {
            userid = userid,
            name = name,
            mobile = mobile,
            department = new[] { 1 } //1就是将用户拉取到列表，不拉取进群
        };
        var apiRes = await _resilienceHttpClient.PostAsync(url2, item);
        return apiRes;
    }

    public async Task<string> WarnGetUser(string userid)
    {
        string accessToken = _sysCacheService.Get<string>(CacheConst.KeyQyvxTokenAddUser);
        if (accessToken == null)
        {
            string url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ww19dea3c4dd73f82a&corpsecret=EKjjfwf7SNytft5opCqgYPHKA6aySQIGAyU_iuzeMwA";
            var tokenRes = await _resilienceHttpClient.GetStringAsync(url);
            var jsonObj = JsonConvert.DeserializeObject<JObject>(tokenRes);
            accessToken = jsonObj["access_token"].Value<string>();
            var expiresIn = jsonObj["expires_in"].Value<int>();
            _sysCacheService.Set(CacheConst.KeyQyvxTokenAddUser, accessToken, TimeSpan.FromTicks(expiresIn * TimeSpan.TicksPerSecond));
        }
        string url2 = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=" + accessToken;
        var item = new
        {
            userid = userid
        };
        var apiRes = await _resilienceHttpClient.PostAsync(url2, item);
        return apiRes;
    }

    public async Task<string> WarnGetUserIds()
    {
        string accessToken = _sysCacheService.Get<string>(CacheConst.KeyQyvxTokenAddUser);
        if (accessToken == null)
        {
            string url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ww19dea3c4dd73f82a&corpsecret=EKjjfwf7SNytft5opCqgYPHKA6aySQIGAyU_iuzeMwA";
            var tokenRes = await _resilienceHttpClient.GetStringAsync(url);
            var jsonObj = JsonConvert.DeserializeObject<JObject>(tokenRes);
            accessToken = jsonObj["access_token"].Value<string>();
            var expiresIn = jsonObj["expires_in"].Value<int>();
            _sysCacheService.Set(CacheConst.KeyQyvxTokenAddUser, accessToken, TimeSpan.FromTicks(expiresIn * TimeSpan.TicksPerSecond));
        }
        string url2 = "https://qyapi.weixin.qq.com/cgi-bin/user/list_id?access_token=" + accessToken;
        var item = new { };
        var apiRes = await _resilienceHttpClient.PostAsync(url2, item);
        return apiRes;
    }

    public async Task<string> WarnAskUser(string userid)
    {
        string accessToken = _sysCacheService.Get<string>(CacheConst.KeyQyvxTokenAddUser);
        if (accessToken == null)
        {
            string url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ww19dea3c4dd73f82a&corpsecret=EKjjfwf7SNytft5opCqgYPHKA6aySQIGAyU_iuzeMwA";
            var tokenRes = await _resilienceHttpClient.GetStringAsync(url);
            var jsonObj = JsonConvert.DeserializeObject<JObject>(tokenRes);
            accessToken = jsonObj["access_token"].Value<string>();
            var expiresIn = jsonObj["expires_in"].Value<int>();
            _sysCacheService.Set(CacheConst.KeyQyvxTokenAddUser, accessToken, TimeSpan.FromTicks(expiresIn * TimeSpan.TicksPerSecond));
        }
        string url2 = "https://qyapi.weixin.qq.com/cgi-bin/batch/invite?access_token=" + accessToken;
        var item = new
        {
            user = new[] { userid }
        };
        var apiRes = await _resilienceHttpClient.PostAsync(url2, item);
        return apiRes;
    }

    [DisplayName("删除企业微信用户")]
    [HttpGet]
    public async Task<string> WchatUserDelete(string userid)
    {
        //string accessToken = _sysCacheService.Get<string>(CacheConst.KeyQyvxTokenAddUser);
        //if (accessToken == null)
        //{
        //    string url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ww19dea3c4dd73f82a&corpsecret=EKjjfwf7SNytft5opCqgYPHKA6aySQIGAyU_iuzeMwA";
        //    var tokenRes = await _resilienceHttpClient.GetStringAsync(url);
        //    var jsonObj = JsonConvert.DeserializeObject<JObject>(tokenRes);
        //    accessToken = jsonObj["access_token"].Value<string>();
        //    var expiresIn = jsonObj["expires_in"].Value<int>();
        //    _sysCacheService.Set(CacheConst.KeyQyvxTokenAddUser, accessToken, TimeSpan.FromTicks(expiresIn * TimeSpan.TicksPerSecond));
        //}
        //string url2 = $"https://qyapi.weixin.qq.com/cgi-bin/user/delete?access_token={accessToken}&userid={userid}";
        //var apiRes = await _resilienceHttpClient.GetStringAsync(url2);
        //return apiRes;
        return "";
    } 
    #endregion

    /// <summary>
    /// 更新用户
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [UnitOfWork]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    [DisplayName("更新用户")]
    public async Task UpdateUser(UpdateUserInput input)
    {
        if (await _sysUserRep.AsQueryable().Filter(null, true).AnyAsync(u => u.Account == input.Account && u.Id != input.Id))
            throw Oops.Oh(ErrorCodeEnum.D1003);

        string remark = string.Empty;
        if (input.RoleIdList != null && input.RoleIdList.Count > 0)
        {
            var roleNames = _sysUserRep.Context.MyQueryable<SysRole>().Where(r => input.RoleIdList.Contains(r.Id))?.Select(r => r.Name).ToList();
            input.Remark = string.Join(",", roleNames);
        }
        await _sysUserRep.AsUpdateable(input.Adapt<SysUser>()).IgnoreColumns(true)
        .IgnoreColumns(u => new { u.AccountType, u.Password, u.Status }).ExecuteCommandAsync();

        await UpdateRoleAndExtOrg(input);

        await OperationWchatUser(input.Adapt<SysUser>());
        // 删除用户机构缓存
        SqlSugarFilter.DeleteUserOrgCache(input.Id, _sysUserRep.Context.CurrentConnectionConfig.ConfigId);
        _sysCacheService.RemoveByPrefixKey(CacheConst.KeyUserButton);
        _sysCacheService.RemoveByPrefixKey(CacheConst.KeyUserAppButton);
        _sysCacheService.RemoveByPrefixKey(CacheConst.KeyUserMenu);
    }

    /// <summary>
    /// 更新角色和扩展机构
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    private async Task UpdateRoleAndExtOrg(AddUserInput input)
    {
        await GrantRole(new UserRoleInput { UserId = input.Id, RoleIdList = input.RoleIdList });

        await _sysUserExtOrgService.UpdateUserExtOrg(input.Id, input.ExtOrgIdList);
    }

    /// <summary>
    /// 删除用户
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [UnitOfWork]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    [DisplayName("删除用户")]
    public async Task DeleteUser(DeleteUserInput input)
    {
        var user = await _sysUserRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        if (user.AccountType == AccountTypeEnum.SuperJR)
            throw Oops.Oh(ErrorCodeEnum.D1014);
        if (user.Id == _userManager.UserId)
            throw Oops.Oh(ErrorCodeEnum.D1001);

        await WchatUserDelete(user.JobNum);
        await _sysUserRep.DeleteAsync(user);


        // 删除用户角色
        await _sysUserRoleService.DeleteUserRoleByUserId(input.Id);

        // 删除用户扩展机构
        await _sysUserExtOrgService.DeleteUserExtOrgByUserId(input.Id);
    }

    /// <summary>
    /// 查看用户基本信息
    /// </summary>
    /// <returns></returns>
    [DisplayName("查看用户基本信息")]
    public async Task<SysUser> GetBaseInfo()
    {

        var user = await _sysUserRep.GetFirstAsync(u => u.Id == _userManager.UserId);
        if (user == null)
            return user;
        var userRoles = await _sysUserRep.Context.Queryable<SysUserRole>()
             .Where(r => r.UserId == user.Id)
             .Includes(r => r.SysRole).ToListAsync();
        if (userRoles != null && userRoles.Count > 0)
            user.MemberLevel = string.Join("、", userRoles.Select(r => r.SysRole.Name).ToList());
        return user;
    }

    /// <summary>
    /// 更新用户基本信息
    /// </summary>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "BaseInfo"), HttpPost]
    [DisplayName("更新用户基本信息")]
    public async Task<int> UpdateBaseInfo(SysUser user)
    {
        return await _sysUserRep.AsUpdateable(user)
            .IgnoreColumns(u => new { u.CreateTime, u.Account, u.Password, u.Avatar, u.AccountType, u.OrgId, u.PosId }).ExecuteCommandAsync();
    }

    /// <summary>
    /// 设置用户状态
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("设置用户状态")]
    public async Task<int> SetStatus(UserInput input)
    {
        var user = await _sysUserRep.GetFirstAsync(u => u.Id == input.Id);
        if (user.AccountType == AccountTypeEnum.SuperJR)
            throw Oops.Oh(ErrorCodeEnum.D1015);

        if (!System.Enum.IsDefined(typeof(StatusEnum), input.Status))
            throw Oops.Oh(ErrorCodeEnum.D3005);

        user.Status = input.Status;
        return await _sysUserRep.AsUpdateable(user).UpdateColumns(u => new { u.Status }).ExecuteCommandAsync();
    }

    /// <summary>
    /// 授权用户角色
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("授权用户角色")]
    public async Task GrantRole(UserRoleInput input)
    {
        var user = await _sysUserRep.GetFirstAsync(u => u.Id == input.UserId);
        if (user.AccountType == AccountTypeEnum.SuperJR)
            throw Oops.Oh(ErrorCodeEnum.D1022);

        await _sysUserRoleService.GrantUserRole(input);
    }

    /// <summary>
    /// 修改用户密码
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("修改用户密码")]
    public async Task<int> ChangePwd(ChangePwdInput input)
    {
        var user = await _sysUserRep.GetFirstAsync(u => u.Id == _userManager.UserId);
        if (CryptogramUtil.CryptoType == CryptogramEnum.MD5.ToString())
        {
            if (user.Password != MD5Encryption.Encrypt(input.PasswordOld))
                throw Oops.Oh(ErrorCodeEnum.D1004);
        }
        else
        {
            if (CryptogramUtil.Decrypt(user.Password) != input.PasswordOld)
                throw Oops.Oh(ErrorCodeEnum.D1004);
        }

        user.Password = CryptogramUtil.Encrypt(input.PasswordNew);
        return await _sysUserRep.AsUpdateable(user).UpdateColumns(u => u.Password).ExecuteCommandAsync();
    }

    /// <summary>
    /// 重置用户密码
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("重置用户密码")]
    public async Task<string> ResetPwd(ResetPwdUserInput input)
    {
        var password = await _sysConfigService.GetConfigValue<string>(CommonConst.SysPassword);
        password = password.Trim();
        var user = await _sysUserRep.GetFirstAsync(u => u.Id == input.Id);
        user.Password = CryptogramUtil.Encrypt(password);
        await _sysUserRep.AsUpdateable(user).UpdateColumns(u => u.Password).ExecuteCommandAsync();
        return password;
    }

    /// <summary>
    /// 获取用户拥有角色集合
    /// </summary>
    /// <param name="userId"></param>
    /// <returns></returns>
    [DisplayName("获取用户拥有角色集合")]
    public async Task<List<long>> GetOwnRoleList(long userId)
    {
        return await _sysUserRoleService.GetUserRoleIdList(userId);
    }

    /// <summary>
    /// 获取用户扩展机构集合
    /// </summary>
    /// <param name="userId"></param>
    /// <returns></returns>
    [DisplayName("获取用户扩展机构集合")]
    public async Task<List<SysUserExtOrg>> GetOwnExtOrgList(long userId)
    {
        return await _sysUserExtOrgService.GetUserExtOrgList(userId);
    }

    [HttpPost]
    public async Task<JRResult<string>> Import(IFormFile file)
    {
        List<SysOrg> newOrgList = new List<SysOrg>();
        IExcelImporter Importer = new ExcelImporter();
        var importDic = await Importer.ImportMultipleSheet<ImportSysUserSysOrgDto>(file.OpenReadStream());
        foreach (KeyValuePair<string, ImportResult<object>> item in importDic)
        {
            var importData = item.Value;
            //if (importData.HasError == true) { return CustomeResult.Fail<string>("导入错误"); }
            if (importData.Exception != null) { return CustomeResult.Fail<string>(importData.Exception.ToString()); }
            if (importData.RowErrors.Count > 0) { return CustomeResult.Fail<string>(JSON.Serialize(importData.RowErrors)); }
            if (importData.Data == null) { return CustomeResult.Fail<string>("导入的数据量不能为空！"); }
            if (importData.Data.Count <= 0) { return CustomeResult.Fail<string>("导入的数据量为0个！"); }

            var _db = _sysUserRep.Context;

            if (item.Key == "组件架构数据")
            {


                var dtos = importData.Data.Adapt<List<ImportSysOrg>>();

                if (dtos.GroupBy(r => r.Code).Any(c => c.Count() > 1)) { return CustomeResult.Fail<string>("sheet[组件架构数据]【部门编码重复】"); }
                if (dtos.GroupBy(r => r.Name).Any(c => c.Count() > 1)) { return CustomeResult.Fail<string>("sheet[组件架构数据]【部门名称重复】"); }
                var orgAlls = await _db.MyQueryable<SysOrg>().ToListAsync();
                if (dtos.Any(r => !r.ParentName.IsNullOrEmpty() && !dtos.Any(c => c.Name == r.ParentName) && !orgAlls.Any(c => c.Name == r.ParentName)))
                    return CustomeResult.Fail<string>("sheet[组件架构数据]【上级部门未在系统和当前Excel中找到】");

                dtos.ForEach(r =>
                {
                    var org = orgAlls.FirstOrDefault(c => c.Code.Trim().ToUpper() == r.Code.Trim().ToUpper());
                    if (org != null)
                        r.Id = org.Id;
                    else
                        r.Id = YitIdHelper.NextId();
                });

                var dbOrgs = await _db.MyQueryable<SysOrg>().Where(r => dtos.Select(c => c.Code.Trim().ToUpper()).Contains(r.Code.Trim().ToUpper())).ToListAsync();
                if (dbOrgs.Count > 0)
                    await _db.MyDeleteable<SysOrg>(dbOrgs).ExecuteCommandAsync();
                for (int i = 0; i < dtos.Count; i++)
                {
                    var dto = dtos[i];
                    var org = dbOrgs.FirstOrDefault(r => r.Code.Trim().ToUpper() == dto.Code.Trim().ToUpper());
                    if (org != null)
                        org.Name = dto.Name;
                    else
                    {
                        org = new SysOrg();
                        org.Id = dto.Id.Value;
                        org.Code = dto.Code;
                        org.Name = dto.Name;
                    }
                    org.MaxCarCount = dto.MaxCarCount;
                    org.MaxCarStopTime = dto.MaxCarStopTime;
                    if (!dto.ParentName.IsNullOrEmpty())
                    {
                        var dbOrg = dtos.FirstOrDefault(r => r.Name == dto.ParentName);
                        if (dbOrg != null)
                            org.Pid = dbOrg.Id.Value;
                        else
                            org.Pid = dbOrgs.FirstOrDefault(r => r.Name == dto.ParentName).Id;
                    }
                    else
                    {
                        org.Pid = orgAlls.FirstOrDefault(r => r.Pid == 0).Id; //挂在台光電子材料（昆山）有限公司
                        org.Level = 2;
                    }
                    newOrgList.Add(org);
                }
                await _db.MyInsertable<SysOrg>(newOrgList).ExecuteCommandAsync();
            }
            else
            {
                var dtos = importData.Data.Adapt<List<ImportSysUser>>();
                if (dtos.GroupBy(r => r.JobNum).Any(c => c.Count() > 1)) { return CustomeResult.Fail<string>("sheet[用户数据]【用户工号重复】"); }
                //if (dtos.GroupBy(r => r.Phone).Any(c => c.Count() > 1)) { return CustomeResult.Fail<string>("sheet[用户数据]【用户手机号重复】"); }
                if (dtos.Any(r => r.Dep.IsNullOrEmpty())) { return CustomeResult.Fail<string>("sheet[用户数据]【用户所属部门存在空数据】"); }
                if (dtos.Any(r => r.Email.IsNullOrEmpty())) { return CustomeResult.Fail<string>("sheet[用户数据]【用户邮箱存在空数据】"); }

                List<SysUser> userList = new List<SysUser>();
                var dbUsers = await _db.MyQueryable<SysUser>().Where(r => dtos.Select(c => c.JobNum.Trim().ToUpper()).Contains(r.JobNum.Trim().ToUpper())).ToListAsync();
                if (dbUsers.Count > 0)
                    await _db.MyDeleteable<SysUser>(dbUsers).ExecuteCommandAsync();

                for (int i = 0; i < dtos.Count; i++)
                {
                    var dto = dtos[i];
                    var user = dbUsers.FirstOrDefault(r => r.JobNum.Trim().ToUpper() == dto.JobNum.Trim().ToUpper());
                    if (user == null)
                    {
                        user = new SysUser();
                        user.Id = YitIdHelper.NextId();
                        user.CardType = CardTypeEnum.IdCard;
                        user.CultureLevel = CultureLevelEnum.Level6;
                        user.OrderNo = i;
                        user.Status = StatusEnum.Enable;
                        user.PosId = 1300000000116;
                        user.AccountType = AccountTypeEnum.NormalUser;
                        user.Age = 18;
                        user.Sex = GenderEnum.Male;
                        user.Password = "04953F80A9877A8C186053E62FEE37CB13DAFE1245B3DEC228F51537ABF863B3085F51E7975D011F57BF1203AD7262FFE87AA64DC1CF309D2098A7D9699EB1887B9A3CF2E889AD433FE46CBD270334D3236E6066F6FB4CCC5D7A451B5972F8F4FB63E0A5D263B2";
                    }
                    user.NickName = user.RealName = dto.Name;
                    user.JobNum = user.Account = dto.JobNum;

                    user.Phone = dto.Phone;
                    //user.IdCardNum = dto.IdCard;
                    user.Birthday = DateTime.Now;
                    //user.Sex = dto.Six == "男" ? GenderEnum.Male : GenderEnum.Female;
                    var dep = newOrgList.FirstOrDefault(r => r.Name == dto.Dep);

                    if (dep != null)
                        user.OrgId = dep.Id;
                    user.Email = dto.Email;

                    await OperationWchatUser(user);
                    userList.Add(user);
                }
                await _db.MyInsertable<SysUser>(userList).ExecuteCommandAsync();
            }
        }
        return CustomeResult.SuccessNotShowMessage<string>();
    }
}

public class dept_user
{
    public string userid { get; set; }
    public int department { get; set; }
}
//dept_user\":[{\"userid\":\"15090\",\"department\":2},{

public class ImportSysUserSysOrgDto
{
    [ExcelImporter(SheetName = "组件架构数据")]
    public ImportSysOrg ImportSysOrgDto { get; set; }
    [ExcelImporter(SheetName = "用户数据")]
    public ImportSysUser ImportSysUserDto { get; set; }
}

[ExcelExporter(Name = "用户数据", TableStyle = OfficeOpenXml.Table.TableStyles.None, AutoFitAllColumn = true, AutoCenter = true)]
[ExcelImporter(IsLabelingError = true, SheetName = "用户数据")]
public class ImportSysUser
{
    /// <summary>
    /// 設備名稱
    /// </summary>
    [ExporterHeader(DisplayName = "姓名", IsBold = true)]
    [ImporterHeader(Name = "姓名")]
    [Required(ErrorMessage = "姓名为必填字段！")]
    public virtual string? Name { get; set; }

    [ExporterHeader(DisplayName = "手机号", IsBold = true)]
    [ImporterHeader(Name = "手机号")]
    [Required(ErrorMessage = "手机号为必填字段！")]
    public virtual string? Phone { get; set; }

    [ExporterHeader(DisplayName = "工号", IsBold = true)]
    [ImporterHeader(Name = "工号")]
    [Required(ErrorMessage = "工号为必填字段！")]
    public virtual string? JobNum { get; set; }

    [ExporterHeader(DisplayName = "所属部门", IsBold = true)]
    [ImporterHeader(Name = "所属部门")]
    [Required(ErrorMessage = "所属部门必填字段！")]
    public virtual string? Dep { get; set; }
    [ExporterHeader(DisplayName = "邮箱地址", IsBold = true)]
    [ImporterHeader(Name = "邮箱地址")]
    [Required(ErrorMessage = "邮箱必填字段！")]
    public virtual string Email { get; set; }

}

[ExcelExporter(Name = "组件架构数据", TableStyle = OfficeOpenXml.Table.TableStyles.None, AutoFitAllColumn = true, AutoCenter = true)]
[ExcelImporter(IsLabelingError = true, SheetName = "组件架构数据")]
public class ImportSysOrg
{
    [ExporterHeader(DisplayName = "部门编码（唯一）", IsBold = true)]
    [ImporterHeader(Name = "部门编码（唯一）")]
    [Required(ErrorMessage = "部门编码为必填字段！")]
    public string Code { get; set; }

    [ExporterHeader(DisplayName = "部门名称", IsBold = true)]
    [ImporterHeader(Name = "部门名称")]
    [Required(ErrorMessage = "部门名称为必填字段！")]
    public string Name { get; set; }

    [ExporterHeader(DisplayName = "上级部门", IsBold = true)]
    [ImporterHeader(Name = "上级部门")]
    public string ParentName { get; set; }


    [ExporterHeader(DisplayName = "最大停车数", IsBold = true)]
    [ImporterHeader(Name = "最大停车数")]
    public int? MaxCarCount { get; set; }

    [ExporterHeader(DisplayName = "最大停车时长/小时", IsBold = true)]
    [ImporterHeader(Name = "最大停车时长/小时")]
    public decimal? MaxCarStopTime { get; set; }

    [ExporterHeader(IsIgnore = true)]
    [ImporterHeader(IsIgnore = true)]
    public long? Id { get; set; }
}